package com.linyaonan.leetcode.easy._917;

/**
 * 给定一个字符串 S，返回 “反转后的” 字符串，其中不是字母的字符都保留在原地，而所有字母的位置发生反转。
 *
 *  
 *
 * 示例 1：
 *
 * 输入："ab-cd"
 * 输出："dc-ba"
 * 示例 2：
 *
 * 输入："a-bC-dEf-ghIj"
 * 输出："j-Ih-gfE-dCba"
 * 示例 3：
 *
 * 输入："Test1ng-Leet=code-Q!"
 * 输出："Qedo1ct-eeLg=ntse-T!"
 *  
 *
 * 提示：
 *
 * S.length <= 100
 * 33 <= S[i].ASCIIcode <= 122 
 * S 中不包含 \ or "
 *
 *
 * @author: Lin
 * @date: 2020/1/12
 */
public class ReverseOnlyLetters {
    public String reverseOnlyLetters(String S) {
        if (S == null || "".equals(S) || S.length() == 1) {
            return S;
        }
        int leftIndex = 0;
        int rightIndex = S.length() - 1;
        StringBuilder sb = new StringBuilder();
        char[] chars = S.toCharArray();
        while (leftIndex < rightIndex) {
            char left = chars[leftIndex];
            char right = chars[rightIndex];

            if (isChar(left) && isChar(right)) {
                chars[rightIndex--] = left;
                chars[leftIndex++] = right;
            } else if (isChar(left)) {
                rightIndex--;
            } else if (isChar(right)) {
                leftIndex++;
            } else {
                rightIndex--;
                leftIndex++;
            }
        }
        for (char c : chars) {
            sb.append(c);
        }
        return sb.toString();
    }

    private boolean isChar(char c) {
        if (c >= 'A' && c <= 'Z') {
            return true;
        } else {
            return c >= 'a' && c <= 'z';
        }
    }
}
